package com.tplhk.thread.future;

import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

/**
 * @ClassName : FutureTest
 * @Description : TODO
 * @Author : jqxu
 * @Date: 2022/4/20 10:34
 **/
//@Service
public class FutureService {

//    @Resource(name="syncExecutorPool")
//    private ThreadPoolTaskExecutor poolTaskExecutor;

    ExecutorService poolTaskExecutor = Executors.newFixedThreadPool(1);

    public String futureSingleTaskTest() throws ExecutionException, InterruptedException {
        //处理单个耗时任务
        Future<String> submit = poolTaskExecutor.submit(new RealData("haha"));
        System.out.println("模拟处理其他业务");
        Thread.sleep(3 * 1000);
        System.out.println("结束其他业务");
        // get 放在最后,如果所有业务处理完，但线程 RealData 还未完成， get() 会等待.
        return submit.get();
    }

    public List<String> futureTest() throws ExecutionException, InterruptedException {
        List<String> dataList = new ArrayList<>();
        for (int i = 0; i < 5; i++) {
            //多线程处理文件:这种处理方式还是阻塞式的，效率很低
            Future<String> submit = poolTaskExecutor.submit(new RealData("haha"));
            String result = submit.get();
            dataList.add(result);
        }

        return dataList;
    }


    public static void main(String[] args) throws ExecutionException, InterruptedException {
        FutureService futureService = new FutureService();
        String s = futureService.futureSingleTaskTest();
        System.out.println("::::::s===" + s);
//        List<String> lists = futureService.futureTest();
//        System.out.println(lists.toString());
    }
}
